package vikaa.timelinepackage;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;



import org.json.JSONObject;

import com.imageFilters.view.PictureFilter;

import vikaa.bean.Formatted_address;
import vikaa.bean.SItude;
import vikaa.tools.DialogService;
import vikaa.tools.HttpUtil;
import vikaa.tools.ImageUtils;
import vikaa.tools.LocationUtil;
import vikaa.tools.Logger;
import vikaa.tools.StringUtils;
import vikaa.ui.Mywowo;
import vikaa.wowo.R;
import vikaa.wowo.cache.AuthoSharePreference;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class TimelineNewMemory extends Activity{
	private LinearLayout backBtn;
	private RelativeLayout camerabtn;
	private ImageView submitBtn;
	private ImageView mImage;
	private RelativeLayout gpsRl;
	private RelativeLayout picLl;
	public static  boolean did = false;
	public String picFile;
	private EditText contentEdt;
	private String space_id;
	private String content;
	private InputMethodManager imm;
	private static String theLarge;
	private File imgFile;
	private TextView addressTv;
	private boolean click = false;
	private String despath = "";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
		setContentView(R.layout.timeline_new_memory);
		addressTv = (TextView)findViewById(R.id.addressTv);
		contentEdt = (EditText)findViewById(R.id.contentEdt);
		space_id = getIntent().getExtras().getString("space_id");
		picLl = (RelativeLayout)findViewById(R.id.picll);
		picLl.setVisibility(View.INVISIBLE);
		mImage = (ImageView)findViewById(R.id.cameraPic);
		camerabtn = (RelativeLayout)findViewById(R.id.cameraRl);
		camerabtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				//picLl.setVisibility(View.INVISIBLE);
				//隐藏软键盘
				imm.hideSoftInputFromWindow(v.getWindowToken(), 0);  
				CharSequence[] items = {
						getString(R.string.img_from_album),
						getString(R.string.img_from_camera)
				};
				imageChooseItem(items);
			}
		});
		gpsRl = (RelativeLayout)findViewById(R.id.GPSBtn);
		gpsRl.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if(!click){
					initLocation();
					addressTv.setVisibility(View.VISIBLE);
					addressTv.setText("获取中");
					click = true;
				}else{
					addressTv.setVisibility(View.INVISIBLE);
					click = false;
				}
			}
		});
		submitBtn = (ImageView)findViewById(R.id.submitBtn);
		submitBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				content = contentEdt.getText().toString();
				content = MyTrim(content);
				if(StringUtils.isEmpty(content) && StringUtils.isEmpty(despath)){
					DialogService.WarnDialog(TimelineNewMemory.this, getString(R.string.tip), getString(R.string.tips_comment_null), getString(R.string.ok));
				}
				else if(despath.length() >0 || content.length() >0){
					imm.hideSoftInputFromWindow(v.getWindowToken(), 0); 
					DialogService.showProgressDialog(TimelineNewMemory.this, getString(R.string.publishing));
					if(!StringUtils.isEmpty(despath)){
						new postImageThread(space_id,despath).start();
					}else if(StringUtils.isEmpty(despath) && !StringUtils.isEmpty(content)){
						new TwitterThread(space_id, content).start();
					}
				}
				/*else
					finish();*/
			}
		});
		backBtn = (LinearLayout)findViewById(R.id.backBtn);
		backBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				finish();
			}
		});
		
		mImage.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if(StringUtils.isEmpty(despath))return;
				Intent i = new Intent(TimelineNewMemory.this,PictureFilter.class);
	        	i.putExtra("path", despath);
	        	i.putExtra("type", 3);
	        	startActivityForResult(i, 10);
			}
		});
		
	}
	public static String MyTrim(String str)
    {
            int start=0,end=str.length()-1;
            while(start<=end && str.charAt(start)==' ')
                    start++;
            while(start<=end && str.charAt(end)==' ')
                    end--;
            return str.substring(start,end+1);
    }
	
	private void initLocation(){
		final Handler handler = new Handler(){
			public void handleMessage(Message msg) {
				if(msg.what == 1 && msg.obj != null){
					addressTv.setText(((Formatted_address)msg.obj).getSublocality().substring(5));
				}
			}
		};
		new Thread(){
			public void run(){
				try {
					SItude itude = LocationUtil.getAltitudeByGPS(TimelineNewMemory.this);
					if(itude == null)itude =  LocationUtil.getAltitudeByBase(TimelineNewMemory.this);
					Formatted_address fa = LocationUtil.getCityByGoogleMap(itude);
					if(fa != null){
						Message msg = new Message();
						msg.what = 1;
						msg.obj = fa;
						handler.sendMessage(msg);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.start();
	}
	@Override 
	protected void onActivityResult(final int requestCode, final int resultCode, final Intent data)	{ 
		if(resultCode != RESULT_OK) return;
    	if(requestCode == ImageUtils.REQUEST_CODE_GETIMAGE_BYSDCARD){
    		if(data == null)  return;
        	
        	Uri thisUri = data.getData();
        	String thePath = ImageUtils.getAbsolutePathFromNoStandardUri(thisUri);
        	//如果是标准Uri
        	if(StringUtils.isEmpty(thePath))
        	{
        		theLarge = ImageUtils.getAbsoluteImagePath(TimelineNewMemory.this,thisUri);
        	}
        	else
        	{
        		theLarge = thePath;
        	}
        	Intent i = new Intent(TimelineNewMemory.this,PictureFilter.class);
        	i.putExtra("path", theLarge);
        	i.putExtra("type", 1);
        	startActivityForResult(i, 10);
    	}
    	
    	if(requestCode == ImageUtils.REQUEST_CODE_GETIMAGE_BYCAMERA){
    		Intent i = new Intent(TimelineNewMemory.this,PictureFilter.class);
    		Logger.i(theLarge);
        	i.putExtra("path", theLarge);
        	i.putExtra("type", 2);
        	startActivityForResult(i, 10);
    	}
    	
    	if(requestCode == 10){
    		Bundle b = data.getExtras();  
            despath = b.getString("despath");
    		final Handler handler = new Handler(){
    			public void handleMessage(Message msg) {
    				if(msg.what == 1 && msg.obj != null){
    					//显示图片
    					mImage.setImageBitmap((Bitmap)msg.obj);
    					mImage.setVisibility(View.VISIBLE);
    					picLl.setVisibility(View.VISIBLE);
    				}
    			}
    		};
    		
    		new Thread(){
    			public void run() 
    			{
				Bitmap bitmap = null;
		        	if(bitmap == null && !StringUtils.isEmpty(despath))
		        	{
		        		bitmap = ImageUtils.loadImgThumbnail(despath, 100, 100);
		        	}
				Message msg = new Message();
				msg.what = 1;
				msg.obj = bitmap;
				handler.sendMessage(msg);
    		        
    			};
    		}.start();
    	}
    }
	/**
	 * 操作选择
	 * @param items
	 */
	public void imageChooseItem(CharSequence[] items )
	{
		AlertDialog imageDialog = new AlertDialog.Builder(this).setTitle(R.string.ui_insert_image).setIcon(android.R.drawable.btn_star).setItems(items,
			new DialogInterface.OnClickListener(){
				public void onClick(DialogInterface dialog, int item)
				{
					/*String savePath = "";
					//判断是否挂载了SD卡
					String storageState = Environment.getExternalStorageState();		
					if(storageState.equals(Environment.MEDIA_MOUNTED)){
						savePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/vikaa/Camera/";//存放照片的文件夹
						File savedir = new File(savePath);
						if (!savedir.exists()) {
							savedir.mkdirs();
						}
					}*/
					//手机选图
					if( item == 0 )
					{
						//mImage.setImageBitmap(null);
						//mImage = null;
						Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
						intent.addCategory(Intent.CATEGORY_OPENABLE); 
						intent.setType("image/*"); 
						startActivityForResult(Intent.createChooser(intent, "选择图片"),ImageUtils.REQUEST_CODE_GETIMAGE_BYSDCARD); 
					}
					//拍照
					else if( item == 1 )
					{	
												
						String savePath = "";
						//判断是否挂载了SD卡
						String storageState = Environment.getExternalStorageState();		
						if(storageState.equals(Environment.MEDIA_MOUNTED)){
							savePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/vikaa/Camera/";//存放照片的文件夹
							File savedir = new File(savePath);
							if (!savedir.exists()) {
								savedir.mkdirs();
							}
						}
						
						//没有挂载SD卡，无法保存文件
						if(StringUtils.isEmpty(savePath)){
							Toast.makeText(getApplicationContext(), getString(R.string.msg_save_image_fail),Toast.LENGTH_SHORT).show();
							return;
						}

						String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
						String fileName = "vikaa_" + timeStamp + ".jpg";//照片命名
						File out = new File(savePath, fileName);
						Uri uri = Uri.fromFile(out);
						
						theLarge = savePath + fileName;//该照片的绝对路径
						Logger.i(theLarge);
						Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
						intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
						startActivityForResult(intent, ImageUtils.REQUEST_CODE_GETIMAGE_BYCAMERA);
					}   
				}}).create();
		
		 imageDialog.show();
	}
	
	Handler mhandler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch(msg.what){
			case 1:
				DialogService.closeProgressDialog();
				String file_id = (String)msg.obj;
				new TwitterThread(space_id, file_id, content).start();
				break;
			case 2:
				DialogService.closeProgressDialog();
				Timeline.isrefresh = true;
				Mywowo.isrefresh = true;
				finish();
				break;
			case 3:
				DialogService.closeProgressDialog();
				if(msg.obj != null){
					Toast.makeText(TimelineNewMemory.this, (String)msg.obj, Toast.LENGTH_SHORT).show();
				}
				else
					Toast.makeText(TimelineNewMemory.this, R.string.server_crash, Toast.LENGTH_SHORT).show();
				break;
			case 4:
				DialogService.closeProgressDialog();
				Toast.makeText(TimelineNewMemory.this, R.string.network_crash, Toast.LENGTH_SHORT).show();
				break;
				
			}
		};
	};
	class postImageThread extends Thread{
		private String space_id;
		private String picpath;
		private boolean isrun = true;
		public postImageThread(String space_id, String picpath) {
			super();
			this.space_id = space_id;
			this.picpath = picpath;
		}
		@Override
		public void run() {
			super.run();
			while(isrun){
				isrun = false;
				try{
					String url = HttpUtil.BASE_URL + "file/upload";
					Map<String,String> map = new HashMap<String, String>();
					map.put("space_id", space_id);
					map.put("PHPSESSID", AuthoSharePreference.getCookie(TimelineNewMemory.this));
					JSONObject jsonObj = new JSONObject(HttpUtil.postFileRequest(url, map, picpath));
					if(jsonObj.getString("result").equals("1")){
						Message msg = mhandler.obtainMessage(1);
						msg.obj = jsonObj.getJSONObject("info").getString("file_id");
						msg.sendToTarget();
					}
					else if(jsonObj.getString("result").equals("0")){
						Message msg = mhandler.obtainMessage(3);
						msg.obj = jsonObj.getString("msg");
						msg.sendToTarget();
					}
					else{
						Message msg = mhandler.obtainMessage(4);
						msg.sendToTarget();
					}
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}
	}
	class TwitterThread extends Thread{
		private String space_id;
		private String file_id;
		private String text;
		private boolean isrun = true;
		Map<String,String> map = new HashMap<String, String>();
		public TwitterThread(String space_id, String file_id, String text) {
			super();
			this.space_id = space_id;
			this.file_id = file_id;
			this.text = text;
			map.put("space_id", space_id);
			map.put("file_id",file_id);
			map.put("file_text", text);
		}
		public TwitterThread(String space_id, String text) {
			super();
			this.space_id = space_id;
			this.text = text;
			map.put("space_id", space_id);
			map.put("file_text", text);
		}
		@Override
		public void run() {
			super.run();
			while(isrun){
				isrun = false;
				try{
					String url = HttpUtil.BASE_URL + "twitter/SaveTextImage";
					JSONObject jsonObj = new JSONObject(HttpUtil.postRequest(url, map));
					if(jsonObj.getString("result").equals("1")){
						Message msg = mhandler.obtainMessage(2);
						//msg.obj = jsonObj.getJSONObject("info").getString("file_id");
						msg.sendToTarget();
					}
					else if(jsonObj.getString("result").equals("0")){
						Message msg = mhandler.obtainMessage(3);
						msg.obj = jsonObj.getString("msg");
						msg.sendToTarget();
					}
					else{
						Message msg = mhandler.obtainMessage(4);
						msg.sendToTarget();
					}
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}
	}
}
